package com.echo.neocommunity.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.echo.neocommunity.pojo.User;
import com.echo.neocommunity.service.impl.FollowService;
import com.echo.neocommunity.service.impl.LikeService;
import com.echo.neocommunity.service.impl.UserServiceImpl;
import com.echo.neocommunity.utils.CommunityConstant;
import com.echo.neocommunity.utils.CommunityUtil;
import com.echo.neocommunity.utils.HostHolder;
import com.echo.neocommunity.utils.R;
import org.apache.catalina.startup.HostConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private LikeService likeService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private HostHolder hostHolder;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${community.path.domain}")
    private String domain;

    @Autowired
    private FollowService followService;

    @GetMapping("/setting")
    public String getSettingPage(){
        return "/site/setting";
    }

    @PostMapping("/upload")
    public String uploadHeaderImage(MultipartFile headerImage, Model model){
        if(headerImage==null){
            model.addAttribute("error","您未选择文件，请选择上传文件！");
            return "/site/setting";
        }
        String filename = headerImage.getOriginalFilename();
        if(filename==null){
            model.addAttribute("error","文件类型错误，请选择.png/.jpeg/.jpg文件！");
            return "/site/setting";
        }
        String suffix=filename.substring(filename.lastIndexOf("."));
        if(StringUtils.isEmpty(suffix) || (!suffix.equals(".png") && !suffix.equals(".jpg") &&!suffix.equals(".jpeg"))){
            model.addAttribute("error","文件类型错误，请选择.png/.jpeg/.jpg文件！");
            return "/site/setting";
        }
        String uploadPath="D:\\Program\\ideal project\\neoCommunity\\src\\main\\java\\com\\echo\\neocommunity\\upload";
        filename= CommunityUtil.generateUUID()+suffix;
        File file=new File(uploadPath+"/"+filename);
        try {
            headerImage.transferTo(file);
            String url=domain+contextPath+"/user/headerimage/"+filename;
            userService.updateUrlHeader(hostHolder.getUser(),url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/index";
    }

    @GetMapping("/headerimage/{filename}")
    public void getHeaderImage(@PathVariable("filename") String filename, HttpServletResponse response){
        String suffix=filename.substring(filename.lastIndexOf("."));
        if(!StringUtils.isEmpty(suffix) && (suffix.equals(".png")|| suffix.equals(".jpg") || suffix.equals(".jpeg")) ){
            try {
                OutputStream os = response.getOutputStream();
                String uploadPath="D:\\Program\\ideal project\\neoCommunity\\src\\main\\java\\com\\echo\\neocommunity\\upload";
                filename=uploadPath+"/"+filename;
                InputStream is=new FileInputStream(filename);
                byte[] data=new byte[1024];
                while(is.read(data)!=-1){
                    os.write(data);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @PostMapping("/updatePassword")
    public String updateUserPassword(String oldPassword,String newPassword,Model model){
        User user = hostHolder.getUser();
        oldPassword=CommunityUtil.md5(oldPassword+user.getSalt());
        if(!user.getPassword().equals(oldPassword)){
            model.addAttribute("errorPassword","原始密码不正确！");
            return "/site/setting";
        }
        userService.updateUserPassword(user,newPassword);
        model.addAttribute("msg","修改密码成功，请重新登录！");
        model.addAttribute("target","/loginOut");
        return "/site/operate-result";
    }

    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId,Model model){
        User user = userService.getUserById(userId);
        if(user==null){
            throw new RuntimeException("该用户不存在！");
        }
        User userNow = hostHolder.getUser();
        boolean isI=userNow.getId()==user.getId();
        long followeeCount = followService.findFolloweeCount(user.getId(), CommunityConstant.ENTITY_TYPE_USER);
        long followerCount = followService.findFollowerCount(CommunityConstant.ENTITY_TYPE_USER, user.getId());
        boolean followeeStatus = followService.findFolloweeStatus(userNow.getId(), CommunityConstant.ENTITY_TYPE_USER, user.getId());
        model.addAttribute("user",user);
        int likeCountTotal = likeService.getLikeCountTotal(user.getId());
        model.addAttribute("likeCount",likeCountTotal);
        model.addAttribute("followeeCount",followeeCount);
        model.addAttribute("followerCount",followerCount);
        model.addAttribute("followeeStatus",followeeStatus);
        model.addAttribute("isI",isI);
        return "/site/profile";
    }



}
